<?php
namespace app\user\controller;
use think\Input;
class Order extends Common{
    public function initialize(){
        parent::initialize();   
        $this->assign('shoplist',cache('shoplist'));   
        $this->assign('cionlist',cache('cionlist')); 
    }

        public function index(){
        if(request()->isPost()){  
            if(input('post.userid')){
                $where['o.userid']=input('post.userid');
            }else{
                $where['o.userid']=session('user.id');
            } 
            $map='';
            $shopid = input('post.shopid');
            if($shopid) $where['shopid']=$shopid;
            $cionid = input('post.cionid');
            if($cionid) $where['cionid']=$cionid;
            $timess = input('post.timess');            
            if($timess){ 
                $timess=explode(" - ",$timess);
                $starttime=strtotime($timess[0]);
                $endtime=strtotime($timess[1])+86399;    
                $map= [$starttime,$endtime];  
            }
            $timequan = input('post.timequan');
            if($timequan) $map= ''.$timequan.''; 
            $orderid = input('post.orderid');
            if($orderid) $where['orderid']=$orderid;
            $orderid_out = input('post.orderid_out');
            if($orderid_out) $where['orderid_out']=$orderid_out;  
            $channelid = input('post.channelid');
            if($channelid) $where['channelid']=$channelid;   

            $state = input('post.state');
            if($state) $where['state']=$state;
            $points = input('post.points');
            if($points)$where['points']=$points;   
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list=db('channel_order')->alias('o')
                ->join(config('database.prefix') . 'user_banks ub', 'o.bankid = ub.id', 'left')
                ->field('o.*,ub.name as payname,ub.bank_no,ub.bank_name')->where('o.state','neq','-1')
                ->where($where)->whereTime('o.addtime',$map)->order('o.id desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();   
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['addtime'] = date('Y-m-d H:i',$v['addtime']);
                if($v['paytime']) $list['data'][$k]['paytime'] = date('Y-m-d H:i',$v['paytime']);
                if($v['state']===0){     
                    $payurl=url('/user/order/uppay',['orderid'=>$v['orderid']]);
                    // $list['data'][$k]['state_name'] ='<a class="layui-btn layui-btn-xs" href="'.$payurl.'"title="如已收支款项，点击可确认付款">待支付</a>';
                    $list['data'][$k]['state_name'] ='<a class="layui-btn layui-btn-xs" href="'.$payurl.'"title="如已收支款项，点击可确认付款" onclick="return window.confirm(\'该笔订单已完成支付？\');">待支付</a>';
                }else if($v['state']===1){
                    // $list['data'][$k]['state_name'] ='<div class="layui-btn layui-btn-normal layui-btn-xs" lay-event="checkpay" title="如您已收到如数款项，请在此确认">待确认</div>';
                }else if($v['state']===2){
                    $list['data'][$k]['state_name'] ='<span class="gre">已确认</span>';
                }else if($v['state']===3){
                    $list['data'][$k]['state_name'] ='<span class="hui">已取消</span>';
                } 
                if($v['points']===0){
                    if($v['state']===2){
                        $list['data'][$k]['points_name'] ='<span class="gre">手动上分</span>';
                        //$list['data'][$k]['points_name'] ='<div class="layui-btn layui-btn-normal layui-btn-xs" lay-event="shangfeng" title="点击上分">去上分</div>';
                    }else{
                        $list['data'][$k]['points_name'] ='<span class="red">待上分</span>';
                    } 
                }else if($v['points']===1){
                    $list['data'][$k]['points_name'] ='<span class="gre">自动上分</span>';
                }else if($v['points']===2){
                    $list['data'][$k]['points_name'] ='<span class="gre">手动上分</span>';
                }
                if($v['fei_user_jie']===0){
                    $list['data'][$k]['fei_user'] ='<span class="red" title="待结算">'.$v['fei_user'].'</span>';
                }else if($v['fei_user_jie']===1){
                    $list['data'][$k]['fei_user'] ='<span class="gre" title="已结算">'.$v['fei_user'].'</span>';
                }
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        // 订单汇总
        $payorder=[];
        $payorder['no']=db('channel_order')->where('userid',session('user.id'))->where('state',0)->sum('money');
        $payorder['que']=db('channel_order')->where('userid',session('user.id'))->where('state',1)->sum('money');
        $payorder['yes']=db('channel_order')->where('userid',session('user.id'))->where('state',2)->sum('money');
        if(!$channelinfo){
            $channelinfo=db('channel')->where('userid',session('user.id'))->select();
            cache('channelinfo',$channelinfo);
        }
        $this->assign('channelinfo',$channelinfo); 
        
        $this->assign('payorder',$payorder);
        $this->assign('title','订单管理');
        return $this->fetch();
    } 

    // public function index(){
    // 	if(request()->isPost()){  
    //         if(input('post.userid')){
    //             $where['o.userid']=input('post.userid');
    //         }else{
    //             $where['o.userid']=session('user.id');
    //         } 
    //         $map='';
    //         $shopid = input('post.shopid');
    //         if($shopid) $where['shopid']=$shopid;
    //         $cionid = input('post.cionid');
    //         if($cionid) $where['cionid']=$cionid;
    //         $timess = input('post.timess');            
    //         if($timess){ 
    //             $timess=explode(" - ",$timess);
    //             $starttime=strtotime($timess[0]);
    //             $endtime=strtotime($timess[1])+86399;    
    //             $map= [$starttime,$endtime];  
    //         }
    //         $timequan = input('post.timequan');
    //         if($timequan) $map= ''.$timequan.''; 
    //         $orderid = input('post.orderid');
    //         if($orderid) $where['orderid']=$orderid;  
    //         $channelid = input('post.channelid');
    //         if($channelid) $where['channelid']=$channelid;   

    //         $state = input('post.state');
    //         if($state) $where['state']=$state;
    //         $points = input('post.points');
    //         if($points)$where['points']=$points;   
    //         $page =input('page')?input('page'):1;
    //         $pageSize =input('limit')?input('limit'):config('pageSize');
    //         $list=db('channel_order')->alias('o')
    //             ->join(config('database.prefix') . 'user_banks ub', 'o.bankid = ub.id', 'left')
    //             ->field('o.*,ub.name as payname,ub.bank_no,ub.bank_name')->where('o.state','neq','-1')
    //             ->where($where)->whereTime('o.addtime',$map)->order('o.id desc')
    //             ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
    //             ->toArray();   
    //         foreach ($list['data'] as $k=>$v){
    //             $list['data'][$k]['addtime'] = date('Y-m-d H:i',$v['addtime']);
    //             if($v['paytime']) $list['data'][$k]['paytime'] = date('Y-m-d H:i',$v['paytime']);
    //             if($v['state']===0){     
    //                 $payurl=url('/pay/pay/gotopay',['orderid'=>$v['orderid'],'appid'=>$v['shopappid'],'sign'=>$v['sign']]);
    //             	$list['data'][$k]['state_name'] ='<a class="layui-btn layui-btn-xs" href="'.$payurl.'" target="_blank" title="如已收支款项，点击可确认付款">待支付</a>';
    //             }else if($v['state']===1){
    //                 $list['data'][$k]['state_name'] ='<div class="layui-btn layui-btn-normal layui-btn-xs" lay-event="checkpay" title="如您已收到如数款项，请在此确认">待确认</div>';
    //             }else if($v['state']===2){
    //                 $list['data'][$k]['state_name'] ='<span class="gre">已确认</span>';
    //             }else if($v['state']===3){
    //                 $list['data'][$k]['state_name'] ='<span class="hui">已取消</span>';
    //             } 
    //             if($v['points']===0){
    //                 if($v['state']===2){
    //                     $list['data'][$k]['points_name'] ='<div class="layui-btn layui-btn-normal layui-btn-xs" lay-event="shangfeng" title="点击上分">去上分</div>';
    //                 }else{
    //                     $list['data'][$k]['points_name'] ='<span class="red">待上分</span>';
    //                 } 
    //             }else if($v['points']===1){
    //                 $list['data'][$k]['points_name'] ='<span class="gre">自动上分</span>';
    //             }else if($v['points']===2){
    //                 $list['data'][$k]['points_name'] ='<span class="gre">手动上分</span>';
    //             }
    //             if($v['fei_user_jie']===0){
    //                 $list['data'][$k]['fei_user'] ='<span class="red" title="待结算">'.$v['fei_user'].'</span>';
    //             }else if($v['fei_user_jie']===1){
    //                 $list['data'][$k]['fei_user'] ='<span class="gre" title="已结算">'.$v['fei_user'].'</span>';
    //             }
    //         }
    //         return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
    //     }
    //     // 订单汇总
    //     $payorder=[];
    //     $payorder['no']=db('channel_order')->where('userid',session('user.id'))->where('state',0)->sum('money');
    //     $payorder['que']=db('channel_order')->where('userid',session('user.id'))->where('state',1)->sum('money');
    //     $payorder['yes']=db('channel_order')->where('userid',session('user.id'))->where('state',2)->sum('money'); 
    //     $this->assign('payorder',$payorder);
    //     $this->assign('title','订单管理');
    //     return $this->fetch();
    // }  
    public function ordermin(){  
        if(input('userid')){
            $this->assign('userid',input('userid')); 
        }else{
            $this->assign('userid',session('user.id')); 
        } 
        $this->assign('channelid',input('channelid')); 
        return $this->fetch();
    }
    // 删除订单
    public function del(){
        if(request()->isPost()){  
            if(db('channel_order')->where(array('id'=>input('id'),'state'=>0,'points'=>0))->update(['state'=>-1])!==false){
                return ['code'=>1,'msg'=>'删除成功！'];
            }else{
                return ['code'=>-1,'msg'=>'该订单不能删除'];
            } 
        }
    }

    //优化代码 订单支付状态变更
    public function uppay(){
        if(request()->isGet()){ 
            $orderid = input('orderid');
            if(db('channel_order')->where(array('orderid'=>$orderid,'state'=>0,'points'=>0))->update(['state'=>2,'points'=>1,'paytime'=>time()])!==false){
                $order=db('channel_order')->where(array('orderid'=>$orderid,'state'=>2,'points'=>1))->find();
                //执行回调
                if($order){  
                //创建签名
                    $requestarray = array(
                        "orderid" =>$order['orderid'],
                        "orderid_out" =>$order['orderid_out'],
                        "money" => $order['money'], 
                        "number" => $order['number'],  
                        "version" => $this->sys['version'] 
                    ); 
                    ksort($requestarray); //按照键名进行升序排序 
                    $Md5key=db('shop')->where('id',$order['shopid'])->value('appkey');
                    $md5str = "";
                    foreach ($requestarray as $key => $val) {
                        $md5str = $md5str . $key . "=" . $val . "&";
                    } 
                    $sign = strtoupper(md5($md5str . "key=" . $Md5key));  //签名转大写
                    
                    // $sign = strtoupper(md5($md5str . "key=" . $Md5key));  //签名转大写
                    $requestarray['sign']=$sign;
                    $requestarray['orderid']=$order['orderid']; 
                    // $requestarray['orderid_out']=$order['orderid_out'];
                    $requestarray["addtime"] = $order['addtime']; 
                    $requestarray["paytime"] = $order['paytime']; 
                    $requestarray["state"] = $order['state']; //0未支付，1已支付未确认，2已经确认
                    $requestarray["points"] = $order['points']; //0未上分，1自动上分，2手动上分    仅state==2,points==0才可上分               
                    if($sign){
                        $notifyurl=$order['notifyurl'];
                        $data_string=json_encode($jsonArr);
                        $curl = curl_init();
                        curl_setopt($curl, CURLOPT_URL,$notifyurl);//设置抓取的url
                        curl_setopt($curl, CURLOPT_HEADER, 'Content-Type:application/x-www-form-urlencoded');//设置头文件的信息作为数据流输出
                        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//设置获取的信息以文件流的形式返回，而不是直接输出。
                        curl_setopt($curl, CURLOPT_POST, 1);//设置post方式提交
                        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
                        curl_setopt($curl, CURLOPT_POSTFIELDS,$md5str."sign=".$requestarray['sign']."&addtime=".$requestarray['addtime']."&paytime=".$requestarray['paytime']."&state=".$requestarray['state']."&points=".$requestarray['points']);
                        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
                        $res_data = curl_exec($curl);//执行命令
                        curl_close($curl);//关闭URL请求   
                        // $res=json_decode($res_data,true);
                        // var_dump($res);
                        echo"<script>alert('操作成功！');history.go(-1);</script>";    
                        die;
                    }
                }
                // echo"<script>alert('操作成功！');history.go(-1);</script>";  
                // die;
                // return ['code'=>1,'msg'=>'操作成功！'];
            }else{
                echo"<script>alert('操作失败！');history.go(-1);</script>"; 
                die;
                // return ['code'=>-1,'msg'=>'订单异常！'];
            } 
        }
    }
    // 订单支付状态变更
    // public function uppay(){
    //     if(request()->isPost()){  
    //         if(db('channel_order')->where(array('id'=>input('id'),'state'=>1,'points'=>0))->update(['state'=>2])!==false){
    //             return ['code'=>1,'msg'=>'操作成功！'];
    //         }else{
    //             return ['code'=>-1,'msg'=>'订单异常！'];
    //         } 
    //     }
    // }
    // 上分处理
    public function gopoints(){
        if(request()->isPost()){  
            $points=input('points');
            $id=input('id');    
            if($points==1){
                // 这里是自动上分的操作
                $shang=$this->gopointsauto($id);
                if($shang['code']===0){
                    db('channel_order')->where(array('id'=>$id,'state'=>2,'points'=>0))->update(['points'=>$points]);
                    return ['code'=>1,'msg'=>'自动上分成功！'];
                }else{
                    return ['code'=>0,'msg'=>'上分失败'];
                }                 
            }else{
                if(db('channel_order')->where(array('id'=>$id,'state'=>2,'points'=>0))->update(['points'=>$points])!==false){
                    return ['code'=>1,'msg'=>'手动上分成功！'];
                }else{
                    return ['code'=>0,'msg'=>'上分失败'];
                }                
            }    
        }
    }
    //自动上分
    public function gopointsauto($id=''){ 
        $order=db('channel_order')->alias('o')->join(config('database.prefix') . 'shop s', 'o.shopid = s.id', 'left')
                ->field('o.*,s.url')->where('o.id',$id)->find();   
        $arr_header[] = "Content-Type:application/json";  
        $url=$order['url']."?orderid=".$order['orderid']."&orderid_out=".$order['orderid_out']."&appid=".$order['shopappid'];  
        $result = http_request_xml($url,$arr_header);   
        $results = json_decode($result,true);   
        if($results['code']===1){ 
            return ['code'=>0,'msg'=>'自动上分成功','acode'=>$results['code']];
        }else{ 
            if($result=='SUCCESS'){
                return ['code'=>0,'msg'=>'自动上分成功','acode'=>$results['code']];
            }else{ 
                return ['code'=>-1,'msg'=>'上分失败','acode'=>$results['code']];
            }
        } 
    }

     public function Post($url,$postfields){
       
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = false; //是否返回响应头信息
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $postfields;
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        curl_setopt_array($ch, $postfields); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接

        return $content;
    }


}